using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using TMM.Common;

namespace TMM
{
    public class LocalData : LocalDataBase
    {
        public const string LocalSettings = "__LocalSettings";
        public Dictionary<string, string> Data { get; private set; }

        private IsolatedStorageFile store = null;

        public LocalData()
        {
            store = IsolatedStorageFile.GetUserStoreForApplication();
            if (!store.FileExists(LocalSettings))
                Data = new Dictionary<string, string>();
            else Data = ReadData();
        }

        private Dictionary<string, string> ReadData()
        {
            try
            {
                using (IsolatedStorageFileStream fs = store.OpenFile(LocalSettings, FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        var content = sr.ReadToEnd();
                        return JsonConvert.DeserializeObject<Dictionary<string, string>>(content);
                    }
                }
            }
            catch (Exception ex)
            {
                //TODO
            }

            return new Dictionary<string, string>();
        }

        private void SaveData()
        {
            using (IsolatedStorageFileStream fs = store.CreateFile(LocalSettings))
            {
                var dataSerialized = JsonConvert.SerializeObject(Data);

                byte[] bytes = new byte[dataSerialized.Length * sizeof(char)];
                System.Buffer.BlockCopy(dataSerialized.ToCharArray(), 0, bytes, 0, bytes.Length);

                fs.Write(bytes, 0, bytes.Length);
            }
        }

        public override T Get<T>(string key)
        {
            try
            {
                if (!Data.ContainsKey(key))
                    return default(T);

                return JsonConvert.DeserializeObject<T>(Data[key]);
            }
            catch (Exception ex)
            {
                //TODO
            }

            return default(T);
        }

        public override void Set<T>(string key, T value)
        {
            if (!Data.ContainsKey(key))
            {
                if (value != null)
                    Data.Add(key, JsonConvert.SerializeObject(value));
            }
            else
            {
                if (value == null)
                    Data.Remove(key);
                else Data[key] = JsonConvert.SerializeObject(value);
            }
        }
    }
}